package com.ding.manager.controller.base;

import com.ding.manager.util.PageData;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.sql.Time;
import java.text.ParseException;
import java.util.*;

/**
 * <pre>
 * 对象功能:BaseController基类
 * 开发人员:lixin
 * 创建时间:2018-01-15
 * </pre>
 */
public class BaseController extends BaseUtil {

	/**
	 * new PageData对象
	 * 
	 * @return
	 */
	public PageData getPageData() {
		return new PageData(this.getRequest());
	}

	/**
	 * 得到ModelAndView
	 * 
	 * @return
	 */
	public ModelAndView getModelAndView() {
		return new ModelAndView();
	}

	/**
	 * 得到request对象
	 * 
	 * @return
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	/**
	 * 得到response对象
	 * 
	 * @return
	 */
	public HttpServletResponse getResponse() {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();

		return response;
	}

	/**
	 * 设置MyBatis分页参数
	 * 
	 * @param request
	 */
	public void setStartPage(HttpServletRequest request) throws Exception {
		// 分页获取列表信息,pageNum:当前页码;pageSize:每页个数
		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isNotEmpty(pageNum) && StringUtils.isNotEmpty(pageSize)) {
			// 如果加上该PageHelper.startPage(MyBatis自带分页操作),那么下一个执行的sql语句会执行分页操作(第二条sql不受影响)
			PageHelper.startPage(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
		} else {
			throw new Exception("pageNum或pageSize为空,无法获取分页数据~");
		}
	}

	/**
	 * 设置MyBatis分页参数
	 */
	public void setStartPage() throws Exception {
		setStartPage(this.getRequest());
	}

	/**
	 * 常量定义
	 */
	private static final String ROOT = "root";

	/* 根对象 */
	private Object root;

	/**
	 * 集合元素名称、类型映射表
	 */
	private Map<String, Class<?>> elementClazzMap = new HashMap<String, Class<?>>();


	/**
	 * 
	 * <p>
	 * 功能描述:获取字段路径
	 * </p>
	 * 
	 * @param k
	 *            索引
	 * @param ks
	 *            字段数组
	 * @return
	 */
	private String getFieldPath(int k, String[] ks) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < k + 1; i++) {
			buf.append(ks[i]).append(".");
		}
		buf.delete(buf.length() - 1, buf.length());
		return buf.toString();
	}

	/**
	 * 
	 * <p>
	 * 功能描述:判断是否为list元素
	 * </p>
	 * 
	 * @param fieldName
	 * @return
	 */
	private boolean isListElement(String fieldName) {
		return !(fieldName.lastIndexOf("[") == -1 && fieldName.lastIndexOf("]") == -1);
	}

}
